<template>
  <div>
    <div class="search-area" style="margin-bottom: 20px">
      <el-input v-model="search.title" placeholder="公告标题" style="width: 200px; margin-right: 20px" />
      <el-select v-model="search.type" placeholder="公告类型" style="width: 200px; margin-right: 20px">
        <el-option label="通知" value="1" />
        <el-option label="公告" value="2" />
      </el-select>
      <el-select v-model="search.status" placeholder="公告状态" style="width: 200px; margin-right: 20px">
        <el-option label="正常" value="0" />
        <el-option label="关闭" value="1" />
      </el-select>
      <el-button @click="searchMethod">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <el-table :data="tableData">
      <el-table-column prop="id" label="公告ID">
      </el-table-column>
      <el-table-column prop="title" label="公告标题">
      </el-table-column>
      <el-table-column prop="content" label="公告内容">
      </el-table-column>
      <el-table-column prop="type" label="公告类型">
        <template #default="{ row }">
          <el-tag v-if="row.type === '1'" type="success">通知</el-tag>
          <el-tag v-else type="danger">公告</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="公告状态">
        <template #default="{ row }">
          <el-tag v-if="row.status === '0'" type="success">正常</el-tag>
          <el-tag v-else type="danger">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间">
      </el-table-column>
      <el-table-column prop="createBy" label="创建者">
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间">
      </el-table-column>
      <el-table-column prop="updateBy" label="更新者">
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openDialog(row)" size="small">编辑</el-button>
          <el-dialog title="编辑公告" v-model="dialogVisible" :append-to-body="true">
            <el-form :model="dialogForm" :rules="rules" ref="dialogFormRef">
              <el-form-item label="公告标题" prop="title">
                <el-input v-model="dialogForm.title" placeholder="请输入公告标题" />
              </el-form-item>
              <el-form-item label="公告内容" prop="content">
                <el-input v-model="dialogForm.content" placeholder="请输入公告内容" />
              </el-form-item>
              <el-form-item label="公告类型" prop="type">
                <el-select v-model="dialogForm.type" placeholder="请选择公告类型">
                  <el-option label="通知" value="1" />
                  <el-option label="公告" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="公告状态" prop="status">
                <el-select v-model="dialogForm.status" placeholder="请选择公告状态">
                  <el-option label="正常" value="0" />
                  <el-option label="关闭" value="1" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleEdit">保存</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
          <el-popconfirm
            title="确定要删除吗？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="handleDelete(row)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="sizes, prev, pager, next, jumper, total"
      @size-change="findSize"
      @current-change="findPage"
      :page-size="pageSize"
      :current-page="currentPage"
      :total="total"
      :page-sizes="[5, 10, 20, 30, 50]"
      style="text-align: center; padding-top: 20px" />

    <el-button @click="toggleAddUserForm" type="success" style="margin-top: 30px">添加公告</el-button>
    <div v-show="showAddForm" class="transition-box" style="margin-top: 20px;">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="form.content" placeholder="请输入公告内容" />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择公告类型">
            <el-option label="通知" value="1" />
            <el-option label="公告" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择公告状态">
            <el-option label="正常" value="0" />
            <el-option label="关闭" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { add, del, getPage, update } from '@/api/Notice.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据
const tableData = ref([])
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)

// 表单
let dialogForm = reactive({
  id: '',
  title: '',
  content: '',
  type: '',
  status: '',
})

const form = reactive({
  id: '',
  title: '',
  content: '',
  type: '',
  status: '',
})

const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
  type: [{ required: true, message: '请输入公告类型', trigger: 'blur' }],
  status: [{ required: true, message: '请输入公告状态', trigger: 'blur' }],
}

const dialogVisible = ref(false)
const showAddForm = ref(false)
const dialogFormRef = ref(null)
const formRef = ref(null)

// 分页方法
const findSize = (size) => {
  pageSize.value = size
  fetchData()
}

const findPage = (page) => {
  currentPage.value = page
  fetchData()
}

// 数据获取和操作方法
const fetchData = async (page = currentPage.value, size = pageSize.value, searchParams = search) => {
  const { data } = await getPage({ pageNum: page, pageSize: size, ...searchParams })
  tableData.value = data.records
  total.value = data.total
}

const openDialog = (row) => {
  dialogVisible.value = true
  Object.assign(dialogForm, row)
}

const handleEdit = async () => {
  dialogFormRef.value.validate().then(() => {
    update(dialogForm).then((res) => {
      if (res.code === 1) {
        ElMessage.success('更新成功')
        fetchData()
        dialogVisible.value = false
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}

const handleDelete = async (row) => {
  del(row.id).then((res) => {
    if (res.code === 1) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  })
}

const toggleAddUserForm = () => {
  showAddForm.value = !showAddForm.value
}

const onSubmit = async () => {
  formRef.value.validate().then(() => {
    add(form).then((res) => {
      if (res.code === 1) {
        ElMessage.success('添加成功')
        fetchData()
        resetForm()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (key === 'title') form[key] = ''
    if (key === 'content') form[key] = ''
    if (key === 'type') form[key] = ''
    if (key === 'status') form[key] = ''
    if (key === 'createTime') form[key] = ''
    if (key === 'createBy') form[key] = ''
    if (key === 'updateTime') form[key] = ''
    if (key === 'updateBy') form[key] = ''
    if (key === 'isDeleted') form[key] = ''
  })
}

// 搜索
const search = reactive({
  title: null,
  type: null,
  status: null,
  createBy: null,
  updateBy: null
})

const searchMethod = () => {
  fetchData(currentPage.value, pageSize.value, search)
}

const resetSearch = () => {
  Object.keys(search).forEach(key => (search[key] = null))
  fetchData()
}


// 加载外键选项数据

onMounted(() => {
  fetchData()
  // 加载所有外键选项数据
})
</script>

<style scoped lang="scss">
.transition-box {
  margin-bottom: 10px;
  width: 100%;
  border-radius: 4px;
  padding: 20px;
  box-sizing: border-box;
}
</style>
